import { Env, RunEnv, Sex } from '@/src/consts'
import dva from '@/src/dva/dva'
import { UserState } from '@/src/dva/models/user'
import Taro from '@tarojs/taro'
import Global from '../global'
// import userData from '@/src/dva/models/user'


export interface Response {
    issuccess: number
    msg: string
    data: any
}

/**
 *  appId配置：测试环境：wxb43681e600225c81
 *             正式环境：wx590c68263ebc1cd4
*/

class Api {

    static readonly baseURL = RunEnv == Env.debug ? "https://api.xiaoludongdong.com" : "https://api.punkyangsheng.com"

    static handleResponse(res?: Response) {
        if (!res) {
            return false
        }

        if (res.issuccess !==1) {
            console.log('resaaaa',res)
            Global.showToast(res.msg)
            return false
        }

        return true
    }
    private static objectToFromData(params: {}) {

        let keys = Object.keys(params)
        let segments = new Array()
        for (const key of keys) {
            segments.push(encodeURIComponent(key) + "=" + encodeURIComponent(params[key]))
        }
        return segments.join("&")
    }

    private static async request(path: string, params: {}): Promise<Response | undefined> {
        let url = Api.baseURL + path
        const user: UserState = dva.app.getStore().getState().user;

        let formData
        if (user.userInfo && user.isLogin) {
            formData = Api.objectToFromData(Object.assign(params, { userid: user.userInfo.userid, token: user.userInfo.token }))
        } else {
            formData = Api.objectToFromData(params)
        }

        // console.log("请求", url, formData)
        // console.log("user", user)
       

        try {
            let resData = await Taro.request({
                url: url,
                data: formData,
                dataType: "json",
                method: "POST",
                header: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                }
            })
            if(!user.isLogin){
                return resData.data
            }
            if(resData.data.isneedlogin==1 && resData.data.msg=='请重新登录'){
                const BaseUrl = path;
                const data = params;
                const dataCode = await Taro.login();
                const ter:any = await this.userWxLogin({code:dataCode.code})
                user.userInfo=ter.data;
                // console.log(user)
                 const datas:any = await this.logInAgain(BaseUrl,data);
                //  console.log('datas',datas)
                return datas
            }else{
                // console.log('resData保存请求',resData)
                return resData.data
            }
            // return resData.data
           
        } catch (error) {
            console.log(error)
        }

        // return resData.data
    }

    static async init() {
        return Api.request("/init.do", {})
    }

    /**
     * 
     * @param params 重新登录
     * @returns 
     */
    static async logInAgain (url,params){
        return Api.request(url, params)
    }
    /**
     * 登录
     * @param params 
     * @returns 
     */
    static async userWxLogin(params: { code: string }) {
        return Api.request("/user/wxlogin.do", params)
    }

    /**
     * 获取个人资料
     * @returns 
     */
    static async userUserData() {
        return Api.request("/user/userdata.do", {})
    }

    /**
     * 修改用户资料
     */
    static async userSetUserInfo(params: {
        nickname: string,
        avatarurl: string,
        province: string | any,
        city: string | any,
        phone: string,
        sex: Sex | any,
        birthday: string
    }) {
        return Api.request("/user/setuserinfo.do", params)
    }

    /**
     * 个人中心数据
     */
    static async userUserCenter() {
        return Api.request("/user/usercenter.do", {})
    }
    /**
     * 请求首页信息
     * @returns 
     */
    static async homeIndex() {
        return Api.request("/index.do", {})
    }


    /**
     * 获取收货地址列表
     */
    static async userGoodsAddressList() {
        return Api.request('/user/goodsaddress_list.do', {})
    }

    /**
     * 添加收货地址
     */
    static async userGoodsAddressAdd(params: {
        name: string//收货人姓名
        phone: string// 收货人号码
        province: any//省
        city: any//市
        area: any // 区
        address: string//详细地址
        isdefault: string//是否是默认收货地址（1：是，0：否）
    }) {
        return Api.request('/user/goodsaddress_add.do', params)
    }

    /**
     * 修改收货地址
     */
    static async userGoodsAddressEdit(params: {
        id: string // 当前收货地址记录ID
        name: string//收货人姓名
        phone: string// 收货人号码
        province: any//省
        city: any//市
        area: any // 区
        address: string//详细地址
        isdefault: string//是否是默认收货地址（1：是，0：否）
    }) {
        return Api.request('/user/goodsaddress_edit.do', params)
    }

    /**
     * 删除收货地址
     * @param params 
     * @returns 
     */
    static async userGoodsAddressDel(params: {
        id: string // 收货地址ID
    }) {
        return Api.request("/user/goodsaddress_del.do", params)
    }

    /**
     * 全部商品列表
     * @param params 
     * @returns 
     */
    static async goodsGoodsList(params: {
        lastid: number // 最后一条记录的specsid，首次加载时，传入0
    }) {
        return Api.request("/goods/goodslist.do", params)
    }

    /**
     * 查看商品详情页
     * @param params 
     */
    static async goodsGoodsInfo(params: {
        id: number //商品Id
    }) {
        return Api.request("/goods/goodsinfo.do", params)
    }

    /**
     * 加入购物车
     * @param params 
     * @returns 
     */
    static async goodsCartAdd(params: {
        goodsid: string[],
        goodsnum?: number
    }) {
        // console.log(typeof params.goodsid)
        return Api.request("/goods/cart_add.do", {
            goodsid: typeof params.goodsid === 'string' ? params.goodsid : params.goodsid.join(" "),
            // goodsid:  params.goodsid.join(" "),
            goodsnum: params.goodsnum ?? 1
        })
    }

    /**
     * 购物车列表页
     * @returns 
     */
    static async goodsCartList() {
        return Api.request("/goods/cart_list.do", {})
    }

    /**
     * 购物车列表-增加减少商品数量
     * @param params 
     */
    static async goodsCartNum(params: {
        goodsid: string,
        addnum: string,
        goodsprice: string
    }) {
        console.log('params', params)
        return Api.request("/goods/cart_num.do", params)
    }

    /**
     * 购物车列表-删除购物车特定商品
     * @param params 
     * @returns 
     */
    static async goodsCartDel(params: {
        idlist: string[]
    }) {
        return Api.request("/goods/cart_del.do", {
            idlist: params.idlist.join(",")
        })
    }

    /**
     *  购物车中，获取当前对应的优惠券的提示信息
     * @param params 
     */
    static async goodsCartGetCouponInfo(params: {
        totalprice: number // 当前用户选择的商品对应的总金额
    }) {
        return Api.request("/goods/cart_getcouponinfo.do", params)
    }

    /**
     * 获取优惠券列表（确认支付时，会选择优惠券）
     * @returns 
     */
    static async goodsCouponList() {
        return Api.request("/goods/coupon_list.do", {})
    }

    /**
     * 要领取的优惠券ID
     */
    static async goodsCouponGet(params: {
        id: string
    }) {
        return Api.request("/goods/coupon_get.do", params)
    }

    /**
     * 确认支付页及增加减少商品数，均按调用这个接口
     */
    static async goodsOrderConfirm(params: {
        // totalprice: number // 当前总金额
        goods_ids: string,
        goods_nums: string,
        type: any
    }) {
        if (params.type == 3) {
            const data = {
                goodsid: params.goods_ids,
                goodsnum: params.goods_nums
            }
            return Api.request("/goods/pintuan_confirm.do", data)
        } else {
            const data = {
                goods_ids: params.goods_ids,
                goods_nums: params.goods_nums
            }
            return Api.request("/goods/order_confirm.do", data)
        }
        // return Api.request("/goods/order_confirm.do", params)
    }

    /**
     * 
     * @param params 
     * @returns
     * orderid  拼团订单id
     * goodsid  拼团商品ID
            goodsnum ： 拼团商品数量，不传时，默认为 1 （后续增加减少数量，）
     */

    static async pintuan_confirm(params: {
        orderid?: string
        goodsid: string
        goodsnum: string
    }) {
        return Api.request("/goods/pintuan_confirm.do", params)
    }

    /**
     * 用户直接下订单
     */
    static async goodsOrderAdd(data: {
        addressid?: string,
        goodsid: string,
        goodsnum: string,
        couponid?: string,
        remark?: string,
        fromcart: number,
        type: string,
        orderid: string
    }) {
        let params = {}
        if (data.type === '3') {
            params = {
                addressid: data.addressid,
                remark: data.remark,
                couponid: data.couponid,
                goodsid: data.goodsid,
                goodsnum: data.goodsnum,
                orderid: data.orderid
            }
            return Api.request("/goods/pintuan_add.do", params)
        } else {
            params = {
                addressid: data.addressid,
                remark: data.remark,
                couponid: data.couponid,
                goodsid: data.goodsid,
                goodsnum: data.goodsnum,
                fromcart: data.fromcart
            }
            return Api.request("/goods/order_add.do", params)
        }

    }

    /**
     * WX支付
     */
    static async orderPayWx(params: {
        orderid: string
    }) {
        return Api.request("/goods/order_pay_wx.do", params)
    }

    // 订单列表
    static async goodsOrderList(params: {
        /*
        0:所有订单
        1:待付款
        2：待发货
        3：待收货
        5：退款/售后
        */
        flag: number,

        // 在分页获取时，最后一条记录的订单号
        lastid: string
    }) {
        return Api.request("/goods/order_list.do", params)
    }

    // 取消订单
    static async goodsOrderCancel(params: {
        orderid: string | any// 订单号,
        cancelreason: string //取消原因
    }) {
        return Api.request("/goods/order_cancel.do", params)
    }


    // 会员积分-积分兑换
    static async userScoreIndex() {
        return Api.request("/user/score_index.do", {})
    }

    // 会员积分-积分明细
    static async userScoreDetail(params: {
        type: number,
        lastid: string
    }) {
        return Api.request("/user/score_detail.do", params)
    }

    /**
     * 订单详情
     */
    static async goodsOrderInfoView(params: {
        orderid: string
    }) {
        return Api.request("/goods/order_info_view.do", params)
    }

    /**
     * 订单中的商品加入购物车
     */
    static async goodsOrderAddToCart(params: {
        orderid: string, // 订单号
        goodid: string, // 订单中商品的记录ID
    }) {
        return Api.request("/goods/order_addtocart.do", params)
    }

    /**
     * 购物车列表 - 清除失效商品
     */
    static async goodsCartClearNoSellGoods() {
        return Api.request("/goods/cart_clearnosellgoods.do", {})
    }

    /**
     * 确认收货信息
     */
    static async goodsOrderReceive(params: {
        orderid: string,
    }) {
        return Api.request("/goods/order_receive.do", params)
    }

    /**
     * 申请退款录入页
     */
    static async goodsOrderBackmoneyInput(params: {
        ordergoodsid: string,
    }) {
        return Api.request("/goods/order_backmoney_input.do", params)
    }


    /**
     * 申请退款提交页
     */
    static async goodsOrderBackmoneyAdd(params: {
        ordergoodsid: string,
        reason: string,
        desc: string
    }) {
        return Api.request("/goods/order_backmoney_add.do", params)
    }

    /**
     * 售后，退款列表
     */
    static async goodsOrderBackmoneyList(params: {
        lastid: string
    }) {
        return Api.request("/goods/order_backmoney_list.do", params)
    }

    /**
     * 退款订单查看页
     */
    static async goodsOrderBackmoneyView(params: {
        id?: string,
        ordergoodsid?: string
    }) {
        return Api.request("/goods/order_backmoney_view.do", params)
    }

    /**
     * 订单支付成功后，点击查看结果时页面
     */
    static async goodsOrderFeedback(params: {
        orderid: string
    }) {
        return Api.request("/goods/order_feedback.do", params)
    }

    /**
     * 将订单的所有商品加入到购物车
     */
    static async goodsOrderAddAllToCart(params: {
        orderid: string
    }) {
        return Api.request("/goods/order_addalltocart.do", params)
    }


    static async getDiscounts(params: {
        lastid: string,
        type: number
    }) {
        return Api.request("/user/usercoupon_list.do", params)
    }

    /**
     * 
     * @param params 
     * @returns  解码手机号码
     */
    static async getPonpe(params: {
        encryptedData: string,
        iv: string,
        code: string
    }) {
        return Api.request("/user/getwxmobile.do", params)
    }
    /**
     * 
     * @returns 获取会员积分
     */
    static async getVip() {
        return Api.request("/user/vipinfo.do", {})
    }
    /**
     * 
     * @param params 
     * @returns 
     * code：wx.login()api调用生成的code
     */

    static async getCheck(params: {
        code: string
    }) {
        return Api.request("/check.do", params)
        // return true
    }
    /**
     * price 价格
     * @param params 
     * @returns 用户下单页面请求可用优惠券信息
     */
    static async currentlist(params: {
        price: string | number | any
    }) {
        return Api.request("/goods/coupon_currentlist.do", params)
    }



    /**
     * 
     * @param params 
     * @returns totalprice : 计算的总金额
     */
    static async getcouponinfo(params: {
        totalprice: any
    }) {
        return Api.request("/goods/getcouponinfo.do", params)
    }

    /**
     * 
     * @param params 
     * orderid : 当前拼团订单id
     */
    static pintuan_detail(params: {
        orderid: string
    }) {
        return Api.request("/goods/pintuan_detail.do", params)
    }




}

export default Api